package com.taofuxn.yycreazy.adpater.base;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.taofuxn.yycreazy.ports.ITaofuAdapterListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用的adapter
 * Created by wanghuafu on 16/9/17.
 */
public abstract class TaofuRecyclerAdapter<T> extends RecyclerView.Adapter<TaofuRecyclerViewHodler> {
    protected int layoutId;
    protected ArrayList<T> mDatas;
    private ITaofuAdapterListener mAdapterListener;

    public TaofuRecyclerAdapter(int layoutId, ArrayList<T> mDatas) {
        this.layoutId = layoutId;
        this.mDatas = mDatas;
    }


    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            if (mAdapterListener != null)
                mAdapterListener.loadMore();
        }
        return super.getItemViewType(position);
    }

    @Override
    public TaofuRecyclerViewHodler onCreateViewHolder(ViewGroup parent, int viewType) {
        View convertView = LayoutInflater.from(parent.getContext())
                .inflate(layoutId, parent, false);
        return new TaofuRecyclerViewHodler(parent.getContext(), convertView);
    }

    @Override
    public void onBindViewHolder(TaofuRecyclerViewHodler holder, int position) {
        convert(holder, mDatas.get(position));

    }

    protected abstract void convert(TaofuRecyclerViewHodler holder, T t);

    @Override
    public int getItemCount() {
        if (mDatas != null)
            return mDatas.size();
        return 0;
    }


    public void setData(ArrayList<T> mData){
        this.mDatas = mData;
        notifyDataSetChanged();
    }

    public void addData(List<T> mData){
        if (mData.size() >0){
            mDatas.addAll(mData);
            notifyItemRangeChanged(mDatas.size() - mData.size(),mDatas.size());
        }

    }

    public void setAdapterListener(ITaofuAdapterListener mAdapterListener){
        this.mAdapterListener = mAdapterListener;
    }

}
